package com.atguigu.gulimall.ssoserver.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController {

    @GetMapping("/login.html")
    public String loginPage(@RequestParam("url")String url, String username,  Model model) {
        model.addAttribute("url", url);
        model.addAttribute("username", username);
        return "login";
    }

    @PostMapping("/doLogin")
    public String login(String username, String password, String url, HttpServletResponse response,
                        @CookieValue(value = "sso_token", required = false)String ssoToken) {
        if (!StringUtils.isEmpty(ssoToken)) {
            //在別的系統已經登錄
            return "redirect:" + url + "?token=" + ssoToken;
        }
        if(!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)){
            // 登录成功跳转 跳回之前的页面
            String uuid = UUID.randomUUID().toString().replace("-", "");
            Cookie cookie = new Cookie("sso_token", uuid);
            response.addCookie(cookie);
//            stringRedisTemplate.opsForValue().set(user.getUser(), uuid, 30, TimeUnit.MINUTES);
            return "redirect:" + url + "?token=" + uuid;
        }
        // 登录失败
        return "login";
    }
}
